﻿using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Collections.Generic;
using StudentManager.API.BLL;
using StudentManager.Data.Model;

namespace StudentManager.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ZbUserInfoController : ControllerBase
    {
        private readonly IZbUserInfoBLL _userBLL;

        public ZbUserInfoController(IZbUserInfoBLL userBLL)
        {
            _userBLL = userBLL;
        }

        // 1. 单条记录查询 - GET: api//5
        [HttpGet("{id}")]
        public async Task<ActionResult<ZbUserInfo>> GetUser(int id)
        {
            var user = await _userBLL.GetUserByIdAsync(id);
            if (user == null)
                return NotFound($"用户ID {id} 不存在");

            return Ok(user);
        }

        // 2. 添加单条记录 - POST: api/
        [HttpPost]
        public async Task<ActionResult> AddUser(ZbUserInfo user)
        {
            try
            {
                var userId = await _userBLL.AddUserAsync(user);
                return CreatedAtAction(nameof(GetUser), new { id = userId }, user);
            }
            catch (System.Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // 3. 修改单条记录 - PUT/5
        [HttpPut("{id}")]
        public async Task<ActionResult> UpdateUser(int id, ZbUserInfo user)
        {
            if (id != user.ZbUserID)
                return BadRequest("ID不匹配");

            var result = await _userBLL.UpdateUserAsync(user);
            if (result)
                return NoContent();

            return BadRequest("更新用户失败");
        }

        // 4. 删除单条记录 - DELETE: api//5
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteUser(int id)
        {
            var result = await _userBLL.DeleteUserAsync(id);
            if (result)
                return NoContent();

            return BadRequest("删除用户失败");
        }

        // 5. 分页与查询 - GET: api/?page=1&size=10&search=keyword
        [HttpGet]
        public async Task<ActionResult> GetUsersPaged(
            [FromQuery] int page = 1,
            [FromQuery] int size = 10,
            [FromQuery] string search = "")
        {
            if (page < 1) page = 1;
            if (size < 1) size = 10;
            if (size > 100) size = 100;

            var (users, totalCount) = await _userBLL.GetPagedListAsync(page, size, search);

            return Ok(new
            {
                Data = users,
                TotalCount = totalCount,
                Page = page,
                PageSize = size,
                TotalPages = (int)System.Math.Ceiling(totalCount / (double)size)
            });
        }
    }
}